package cn.yshujia.repository;

import cn.yshujia.domain.dto.PageDTO;
import cn.yshujia.domain.entity.TreeHole;
import cn.yshujia.domain.vo.PageVO;
import cn.yshujia.mapper.TreeHoleMapper;
import cn.yshujia.utils.PageUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Repository;
import org.springframework.util.ObjectUtils;

import java.time.Duration;
import java.util.List;

/**
 * @author YShuJia
 * @create 2024/12/18
 * @description TreeHoleRepository
 */

@Repository
public class TreeHoleRepository {
	
	@Resource
	RedisTemplate<String, TreeHole> redis;
	
	@Resource
	TreeHoleMapper mapper;
	
	private static final String LIST = "tree_hole:list";
	
	private static final Duration DURATION = Duration.ofDays(3L);
	
	public PageVO<TreeHole> page(PageDTO dto) {
		long start = (long) (dto.getCurrent() - 1) * dto.getSize();
		long end = start + dto.getSize() - 1;
		List<TreeHole> list = redis.opsForList().range(LIST, start, end);
		if (!ObjectUtils.isEmpty(list)) {
			return PageUtils.getPage(dto, list);
		}
		list = mapper.selectListByWrapper(new LambdaQueryWrapper<TreeHole>().orderByDesc(TreeHole::getCreateTime));
		if (!ObjectUtils.isEmpty(list)) {
			redis.opsForList().rightPushAll(LIST, list);
			redis.opsForList().getOperations().expire(LIST, DURATION);
			list = redis.opsForList().range(LIST, start, end);
		}
		return PageUtils.getPage(dto, list);
	}
	
	@Async ("Task")
	public void del() {
		redis.delete(LIST);
	}
}
